package com.drotposta.unitils;

import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.GenericServlet;

/**
 *
 * @author elek
 */
public class ServletFactory<T extends GenericServlet> {

    T servlet;

    Directory directory;

    Injector ejbInjector = new BaseInjector() {

        @Override
        public Object getValueToInject(Object bean, Field field, Class annotation) {
            return new EjbFactory(field.getType(), directory).getEjb();
        }
    };

    public ServletFactory(Class<T> servletClass, Directory directory) {
        try {
            this.directory = directory;
            this.servlet = servletClass.newInstance();
            this.servlet.init();
            ejbInjector.inject(this.servlet, EJB.class);
        } catch (Exception ex) {
            Logger.getLogger(ServletFactory.class.getName()).log(Level.SEVERE, null, ex);
            throw new RuntimeException("Servlet initialization failed");
        }
    }

    public T getServlet() {
        return servlet;
    }
}
